package com.yhos.platform.oopston.core.handler;


import com.yhos.platform.oopston.core.utils.DateUtils;
import com.yhos.platform.oopston.core.utils.JacksonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public abstract class InterceptorHandler {

    private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(InterceptorHandler.class);
    public static String IS_AJAX_REQUEST = "IS_AJAX_REQUEST";

    //本应用跳转地址
    private String redirectUrl;

    public String getRedirectUrl() {
        return redirectUrl;
    }

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    public void printErrorInfo(HttpServletRequest request, HttpServletResponse response, String code, String message) throws IOException {
        String isAjaxRequest = request.getHeader(IS_AJAX_REQUEST);
        if ("1".equals(isAjaxRequest)) {
            printJsonInfo(request, response, code, message);
        } else {
            response.sendRedirect(redirectUrl);
        }
    }

    public void printJsonInfo(HttpServletRequest request, HttpServletResponse response, String code, String message) throws IOException {
        Map map = new HashMap();
        map.put("success", code);
        map.put("msg", message);
//        map.put("redirectUrl", getRedirectUrl());
        map.put("ret", "LOGIN_TIME_OUT_ERROR");
        map.put("responseTime", DateUtils.dateToString(new Date()));

        // 返回字符串
        String result;
        try {
            result = JacksonUtils.getInstance().writeValueAsString(map);
        } catch (Exception e) {
            result = "";
            logger.error("InterceptorHandler printOut convert json error. " + e.getMessage(), e);
        }

        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(result);
        writer.flush();
        writer.close();
    }

    public abstract Boolean doHandler(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;

}
